package com.cap.bts.crmdp.dealer.meal.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.card.domain.CardDefinition;
import com.cap.bts.crmdp.dealer.card.service.ICardDefineService;
import com.cap.bts.crmdp.dealer.coupon.constants.CouponConstants;
import com.cap.bts.crmdp.dealer.coupon.domain.Ticket;
import com.cap.bts.crmdp.dealer.coupon.domain.TicketLine;
import com.cap.bts.crmdp.dealer.coupon.service.ITicKetDefineService;
import com.cap.bts.crmdp.dealer.meal.constants.MealConstants;
import com.cap.bts.crmdp.dealer.meal.domain.MealModel;
import com.cap.bts.crmdp.dealer.meal.domain.MeallineModel;
import com.cap.bts.crmdp.dealer.meal.domain.PackageDealerSelected;
import com.cap.bts.crmdp.dealer.meal.domain.PackageEligibilityModel;
import com.cap.bts.crmdp.dealer.meal.dto.MealDefineDto;
import com.cap.bts.crmdp.dealer.meal.dto.MealLineDto;
import com.cap.bts.crmdp.dealer.meal.dto.MealLineResultDto;
import com.cap.bts.crmdp.dealer.meal.dto.PackageEligibilityDto;
import com.cap.bts.crmdp.dealer.meal.dto.PackageGiftDto;
import com.cap.bts.crmdp.dealer.meal.dto.ResultDto;
import com.cap.bts.crmdp.dealer.meal.service.IMealManageService;
import com.cap.bts.crmdp.dealer.packagegift.domain.MemberGiftInfo;
import com.cap.bts.crmdp.dealer.packagegift.dto.MermberGiftDto;
import com.cap.bts.crmdp.dealer.packagegift.service.IMemberGiftService;
import com.cap.bts.crmdp.dealer.purchase.service.IPackageDefinitionService;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.dto.CodeInfoDto;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Pager;
import com.cap.bts.framework.common.util.Utils;

/**
 * 套餐管理controller
 * 
 * @author liZhiYong
 * @version $Id: MealController.java, v 0.1 2015-9-14 下午1:53:38 1111 Exp $
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/meal")
public class MealController extends BaseController {
    private static final Logger LOGGER            = Logger.getLogger(MealController.class);

    @Autowired
    IMealManageService          iMealManageService;

    @Autowired
    ITicKetDefineService        iTicKetDefineService;

    @Autowired
    ICardDefineService          cardDefineService;

    @Autowired
    IMemberGiftService          iMemberGiftService;

    @Autowired
    ICodeMapping                iCodeMapping;
    
    @Autowired
    IPackageDefinitionService packageDefinitionService;

    private List<Ticket>        ticketList        = null;

    private static final String TICKETLIST        = "ticketList";

    private static final String PREPAYAMOUNT      = "prepayAmount";

    private static String       QSTATUS           = "qStatus";

    private static String       QNAME             = "qName";

    private static String       QCODE             = "qCode";

    private static String       PAGER_CURRENTPAGE = "pager.currentPage";

    private static String       CURRENTPAGE       = "currentPage";

    /**
     * 套餐定义页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toQueryMeal")
    public String toQueryMeal(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                         throws AppException {
        if ("query".equals(request.getParameter("temp"))) {
            List<MealModel> mealList = iMealManageService.getMealLIst(dto);
            model.addAttribute("mealList", mealList);
            model.addAttribute("dto", dto);
            model.addAttribute(QCODE, dto.getCode());
            model.addAttribute(QNAME, dto.getName());
            model.addAttribute(QSTATUS, dto.getStatus());
            model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        }else{
            Pager pager = new Pager();
            pager.setCurrentPage(1);
            MealDefineDto mealDefineDto = new MealDefineDto();
            mealDefineDto.setPager(pager);
            getMealList(mealDefineDto, model, request);
        }
        return "/meal/mealQuery";
    }

    /**
     * 套餐信息查询
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "getMealList")
    public String getMealList(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                         throws AppException {
        String code = dto.getqCode();
        if (code != null) {
            dto.setCode(code);
        }
        String name = dto.getqName();
        if (name != null) {
            dto.setName(name);
        }
        String status = dto.getqStatus();
        if (StringUtils.isNotBlank(status)) {
            dto.setStatus(Byte.valueOf(status));
        }
        List<MealModel> mealList = iMealManageService.getMealLIst(dto);

        model.addAttribute("mealList", mealList);
        model.addAttribute("dto", dto);
        model.addAttribute(QCODE, code);
        model.addAttribute(QNAME, name);
        model.addAttribute(QSTATUS, status);
        model.addAttribute(CURRENTPAGE, dto.getPager().getCurrentPage());
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());

        if ("enabled".equals(request.getParameter("temp"))) {
            return "/meal/packageEnabled";
        }
        return "/meal/mealQuery";
    }

    /**
     * 套餐定义页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "toMealDefine")
    public String toMealDefine(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                          throws AppException {
        List<CardDefinition> list = cardDefineService.getCardList();
        ticketList = iTicKetDefineService.getAllTicketList();

        List<ResultDto> resultList = getResultDtoList(dto, ticketList);

        for (Iterator iterator = ticketList.iterator(); iterator.hasNext();) {
            Ticket ticket = (Ticket) iterator.next();
            setTicketTypeCode(ticket);
        }

        model.addAttribute(QNAME, dto.getName());
        model.addAttribute(QCODE, dto.getCode());
        model.addAttribute(QSTATUS, dto.getStatus());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));

        model.addAttribute("cardList", list);
        model.addAttribute(TICKETLIST, ticketList);
        model.addAttribute("resultList", resultList);
        return "/meal/insertMeal";
    }

    /**
     * 套餐新增
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "saveMeal")
    @ResponseBody
    public Map<String, Object> saveMeal(MealDefineDto dto, Model model, HttpServletRequest request) {

        Map<String, Object> jsonMap = new HashMap<String, Object>();
        MealModel mealModel;
        try {
            dto.setCardDefId(Long.valueOf(request.getParameter("cardId")));
            // 判断套餐是否重复
            mealModel = iMealManageService.getMealInfoByCode(dto);
            if (mealModel != null) {
                jsonMap.put("msg", dto.getCode() + "套餐已存在，不能重复新增");
                jsonMap.put("code", false);
                return jsonMap;
            }

            // 取得该卡是实物卡还是非实物卡
            List<CardDefinition> cardList = cardDefineService.getCardList();
            if (!cardList.isEmpty()) {
                for (Iterator iterator = cardList.iterator(); iterator.hasNext();) {
                    CardDefinition cardDefinition = (CardDefinition) iterator.next();
                    if (dto.getCardDefId().equals(cardDefinition.getId())) {
                        dto.setIsPhysicalCard(cardDefinition.getIsPhysicalCard());
                        break;
                    }
                }
            }

            if ("".equals(dto.getDataStr())) {
                jsonMap.put("code", false);
                jsonMap.put("msg", "套餐详细不能为空");
                return jsonMap;
            }
            //套餐信息新增
            MealDefineDto mealDefineDto = iMealManageService.insertMealInfo(dto);
            if (!mealDefineDto.isFlag()) {
                jsonMap.put("code", false);
                jsonMap.put("msg", dto.getCode() + MealConstants.MEAL_ERROR_MSG);
                LOGGER.error(dto.getCode() + MealConstants.MEAL_ERROR_MSG);
                return jsonMap;
            }
        } catch (AppException e) {
            jsonMap.put("code", false);
            jsonMap.put("msg", dto.getCode() + MealConstants.MEAL_ERROR_MSG);
            LOGGER.error(dto.getCode() + MealConstants.MEAL_ERROR_MSG, e);
            return jsonMap;
        }

        jsonMap.put("code", true);
        jsonMap.put("msg", dto.getCode() + "套餐新增成功");
        return jsonMap;
    }

    /**
     * 根据优惠券和提货券ID查询其详细信息
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "getTicKetLineInfo")
    @ResponseBody
    public Map<String, Object> getTicKetLineInfo(MealDefineDto dto, Model model,
                                                 HttpServletRequest request) {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        String ticketId = request.getParameter("ticketId");
        try {
            List<TicketLine> ticketlineList = iTicKetDefineService.getTicketLineInfoList(ticketId);

            if (!ticketlineList.isEmpty()) {
                Double prepayAmount = 0.00;
                for (Iterator iterator = ticketlineList.iterator(); iterator.hasNext();) {
                    TicketLine ticketLine = (TicketLine) iterator.next();
                    if (Long.valueOf(ticketId).equals(ticketLine.getTicketDefId())) {
                        prepayAmount = prepayAmount + ticketLine.getPrepayAmount();
                    }
                }
                jsonMap.put("code", true);
                jsonMap.put(PREPAYAMOUNT, prepayAmount);
                return jsonMap;
            } else {
                jsonMap.put("code", false);
                jsonMap.put(PREPAYAMOUNT, 0);
                jsonMap.put("msg", "数据库数据不正确");
                return jsonMap;
            }
        } catch (AppException e) {
            LOGGER.error("", e);
            jsonMap.put("msg", "内部错误");
        }

        return jsonMap;
    }

    /**
     * 修改套餐页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "toEditMealPage")
    public String toEditMealPage(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                            throws AppException {

        String mealId = request.getParameter("id");
        if (!Utils.isNullOrEmpty(mealId)) {
            // 获取卡片类型
            List<CardDefinition> list = cardDefineService.getCardList();
            // 获取优惠券和提货券信息
            ticketList = iTicKetDefineService.getAllTicketList();
            for (Iterator iterator = ticketList.iterator(); iterator.hasNext();) {
                Ticket ticket = (Ticket) iterator.next();
                setTicketTypeCode(ticket);
            }

            dto.setId(Long.valueOf(mealId));
            // 获取套餐信息
            MealModel mealModel = iMealManageService.getMealInfoById(dto);

            // 获取套餐的详细信息
            List<MealLineResultDto> mealLineResultList = iMealManageService.getMeallineList(dto);

            double sumAmount = 0.0;

            for (Iterator iterator = mealLineResultList.iterator(); iterator.hasNext();) {
                MealLineResultDto mealLineResultDto = (MealLineResultDto) iterator.next();

                // 根据ticketId查询优惠券和提货券的详细信息
                Long ticketId = mealLineResultDto.getTicketDefId();
                List<TicketLine> ticketlineList = iTicKetDefineService.getTicketLineInfoList(Long
                    .toString(ticketId));

                if (!ticketlineList.isEmpty()) {
                    Double prepayAmount = 0.00;
                    for (Iterator iterator2 = ticketlineList.iterator(); iterator2.hasNext();) {
                        TicketLine ticketLine = (TicketLine) iterator2.next();
                        if (ticketId.equals(ticketLine.getTicketDefId())) {
                            prepayAmount = prepayAmount + ticketLine.getPrepayAmount();
                        }
                    }
                    double amount = prepayAmount * mealLineResultDto.getNumberOfUse();
                    BigDecimal bigAmount = new BigDecimal(amount);

                    amount = bigAmount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    mealLineResultDto.setPrepayAmount(amount);
                    sumAmount = sumAmount + amount;
                }
            }

            model.addAttribute("sumAmount", sumAmount);
            model.addAttribute(QNAME, dto.getqName());
            model.addAttribute(QCODE, dto.getqCode());
            model.addAttribute(QSTATUS, dto.getqStatus());
            model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));

            model.addAttribute("mealModel", mealModel);
            model.addAttribute("cardList", list);
            model.addAttribute(TICKETLIST, ticketList);

            model.addAttribute("dto", dto);
            model.addAttribute("mealLineResultList", mealLineResultList);
        }
        if ("details".equals(request.getParameter("temp"))) {

            List<PackageGiftDto> pGiftDtoList = new ArrayList<PackageGiftDto>();
            PackageGiftDto packageGiftDto = null;

            //根据套餐ID查询套餐礼物信息
            List<MemberGiftInfo> meInfoList = iMemberGiftService.getGiftByPackageDefId(dto.getId());
            for (Iterator iterator = meInfoList.iterator(); iterator.hasNext();) {
                MemberGiftInfo memberGiftInfo = (MemberGiftInfo) iterator.next();
                packageGiftDto = new PackageGiftDto();

                packageGiftDto.setId(memberGiftInfo.getId());
                packageGiftDto.setPackageId(memberGiftInfo.getPackageId());
                packageGiftDto.setGiftType(memberGiftInfo.getGiftType());
                packageGiftDto.setGiftId(memberGiftInfo.getGiftId());

                if (MealConstants.CRAD_TYPE_PACKAGE.equals(memberGiftInfo.getGiftType())) {
                    //根据套餐ID查询套餐信息
                    MealDefineDto mealDefineDto = new MealDefineDto();
                    mealDefineDto.setId(memberGiftInfo.getGiftId());
                    MealModel mealModel = iMealManageService.getMealInfoById(mealDefineDto);
                    packageGiftDto.setGiftName(mealModel.getName());
                } else if (CouponConstants.TICKET_TYPE_COUPON.equals(memberGiftInfo.getGiftType())
                           || CouponConstants.TICKET_TYPE_REDEMPTION.equals(memberGiftInfo
                               .getGiftType())) {
                    Ticket ticket = iTicKetDefineService.getTicketById(memberGiftInfo.getGiftId()
                        .toString());
                    packageGiftDto.setGiftName(ticket.getTicketName());
                }
                pGiftDtoList.add(packageGiftDto);
            }
            
            //根据套餐ID查询套餐的适用范围信息
            PackageEligibilityDto packageEligibilityDto = new PackageEligibilityDto();
            packageEligibilityDto.setPackageDefId(dto.getId());

            List<PackageEligibilityModel> packageEligibilityList = iMealManageService
                .getPackageEligibilityList(packageEligibilityDto);
            for (Iterator iterator = packageEligibilityList.iterator(); iterator.hasNext();) {
                PackageEligibilityModel packageEligibilityModel = (PackageEligibilityModel) iterator
                    .next();
                String value = iCodeMapping.getCodeValueByCode(MealConstants.CODE_TYPE_DEALERPROPERTY, packageEligibilityModel.getDealerProperty());
                packageEligibilityModel.setDealerProperty(value);
            }

            model.addAttribute("packageEligibilityList", packageEligibilityList);
            model.addAttribute("pGiftDtoList", pGiftDtoList);
            return "/meal/packageDetails";
        }
        return "/meal/editMeal";
    }

    /**
     * 修改套餐
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "updateMealInfo")
    @ResponseBody
    public Map<String, Object> updateMealInfo(MealDefineDto dto, Model model,
                                              HttpServletRequest request) throws AppException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        MealModel mealModel = iMealManageService.getMealInfoById(dto);
        if (mealModel != null) {
            Long status = mealModel.getStatus().longValue();
            if ((status == MealConstants.MEAL_STATUS_ACTIVE.longValue() || status == MealConstants.MEAL_STATUS_DISCONTINUED
                .longValue())
                && dto.getStatus().longValue() == MealConstants.MEAL_STATUS_DRAFT.longValue()) {

                jsonMap.put("code", false);
                jsonMap.put("msg", "【有效和停用状态】 的套餐不能修成【未启用】的套餐");
                return jsonMap;
            }

            // 取得该卡是实物卡还是非实物卡
            List<CardDefinition> cardList = cardDefineService.getCardList();
            if (!cardList.isEmpty()) {
                for (Iterator iterator = cardList.iterator(); iterator.hasNext();) {
                    CardDefinition cardDefinition = (CardDefinition) iterator.next();
                    if (dto.getCardDefId().equals(cardDefinition.getId())) {
                        dto.setIsPhysicalCard(cardDefinition.getIsPhysicalCard());
                        break;
                    }
                }
            }

            if (iMealManageService.updateMealInfo(dto)) {
                jsonMap.put("code", true);
                jsonMap.put("msg", "修改成功");
                return jsonMap;
            }
        }
        jsonMap.put("code", false);
        jsonMap.put("msg", "修改失败");
        return jsonMap;

    }

    /**
     * 查看套餐详情
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "getMealLineInfo")
    public String getMealLineInfo(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                             throws AppException {

        // 获取套餐的详细信息
        List<MealLineResultDto> mealLineResultList = iMealManageService.getMeallineList(dto);
        model.addAttribute("mealLineResultList", mealLineResultList);
        return "/meal/selectMealLine";
    }

    /**
     * 删除套餐信息
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "removeMealInfo")
    @ResponseBody
    public Map<String, Object> removeMealInfo(MealDefineDto dto, Model model,
                                              HttpServletRequest request) throws AppException {

        Map<String, Object> jsonMap = new HashMap<String, Object>();
        MealModel mealModel = iMealManageService.getMealInfoById(dto);
        if (mealModel != null) {
            if (mealModel.getStatus().longValue() == MealConstants.MEAL_STATUS_DRAFT.longValue()) {//未启用
                iMealManageService.removeMealById(mealModel.getId());
                jsonMap.put("code", true);
                jsonMap.put("msg", "删除成功");
                return jsonMap;
            } else {
                jsonMap.put("code", false);
                jsonMap.put("msg", "只有状态未启用的套餐才能删除");
                return jsonMap;
            }
        }
        jsonMap.put("code", false);
        jsonMap.put("msg", "删除失败");
        return jsonMap;
    }

    /**
     * 套餐详细信息修改初始化页面
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "toMealLineInfo")
    public String toMealLineInfo(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                            throws AppException {

        ticketList = iTicKetDefineService.getAllTicketList();
        for (Iterator iterator = ticketList.iterator(); iterator.hasNext();) {
            Ticket ticket = (Ticket) iterator.next();
            setTicketTypeCode(ticket);
        }

        // 获取套餐的详细信息
        MeallineModel meallineModel = iMealManageService.getMealLIneInfo(dto.getId());

        MealLineDto mealLineDto = new MealLineDto();
        mealLineDto.setId(meallineModel.getId());
        mealLineDto.setPackageDefId(meallineModel.getPackageDefId());
        mealLineDto.setShortName(meallineModel.getShortName());
        mealLineDto.setDescription(meallineModel.getDescription());
        mealLineDto.setNumberOfUse(meallineModel.getNumberOfUse());
        mealLineDto.setHasVerificationCode(meallineModel.getHasVerificationCode());
        mealLineDto.setTicketDefId(meallineModel.getTicketDefId());

        // 根据ticketId查询优惠券和提货券的详细信息
        Long ticketId = meallineModel.getTicketDefId();
        List<TicketLine> ticketlineList = iTicKetDefineService.getTicketLineInfoList(Long
            .toString(ticketId));

        if (!ticketlineList.isEmpty()) {
            Double prepayAmount = 0.00;
            for (Iterator iterator = ticketlineList.iterator(); iterator.hasNext();) {
                TicketLine ticketLine = (TicketLine) iterator.next();
                if (ticketId.equals(ticketLine.getTicketDefId())) {
                    prepayAmount = prepayAmount + ticketLine.getPrepayAmount();
                }
            }
            double amount = prepayAmount * mealLineDto.getNumberOfUse();
            BigDecimal bigAmount = new BigDecimal(amount);

            amount = bigAmount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            mealLineDto.setPrepayAmount(amount);
            mealLineDto.setOnePrice(prepayAmount);
        }

        Ticket ticket = iTicKetDefineService.getTicketById(Long.toString(ticketId));
        if (ticket != null) {
            setTicketTypeCode(ticket);
            mealLineDto.setTicketType(ticket.getTicketType());
        }

        model.addAttribute(TICKETLIST, ticketList);
        model.addAttribute("mealLineDto", mealLineDto);
        model.addAttribute(QNAME, dto.getqName());
        model.addAttribute(QCODE, dto.getqCode());
        model.addAttribute(QSTATUS, dto.getqStatus());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));

        return "/meal/updateMealLine";
    }

    /**
     * 套餐详细信息修改
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "updateMealLineInfo")
    @ResponseBody
    public Map<String, Object> updateMealLineInfo(MealDefineDto dto, Model model,
                                                  HttpServletRequest request) throws AppException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();

        Long ticketDefId = dto.getTicketDefId();
        if (Utils.notNullAndZero(ticketDefId)) {
            Ticket ticket = iTicKetDefineService.getTicketById(Long.toString(ticketDefId));

            if (MealConstants.VERIFICATION_METHOD_CODE.equals(ticket.getVerificationMethod())) {
                dto.setHasVerificationCode("Y");
            } else if (MealConstants.VERIFICATION_METHOD_N.equals(ticket.getVerificationMethod())) {
                dto.setHasVerificationCode("N");
            }

        }
        if (iMealManageService.updateMealLineInfo(dto)) {
            jsonMap.put("code", true);
            jsonMap.put("msg", "修改成功");
            return jsonMap;
        }
        jsonMap.put("code", false);
        jsonMap.put("msg", "修改失败");
        return jsonMap;
    }

    /**
     * 新增套餐详细页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "saveMealLineDetails")
    public String saveMealLineDetails(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                                 throws AppException {

        ticketList = iTicKetDefineService.getAllTicketList();
        for (Iterator iterator = ticketList.iterator(); iterator.hasNext();) {
            Ticket ticket = (Ticket) iterator.next();
            setTicketTypeCode(ticket);
        }
        model.addAttribute("packageDefId", dto.getPackageDefId());
        model.addAttribute(TICKETLIST, ticketList);
        model.addAttribute(QNAME, dto.getqName());
        model.addAttribute(QCODE, dto.getqCode());
        model.addAttribute(QSTATUS, dto.getqStatus());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        return "/meal/insertMealLine";
    }

    /**
     * 套餐详细信息新增
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "saveMealLineInfo")
    @ResponseBody
    public Map<String, Object> saveMealLineInfo(MealDefineDto dto, Model model,
                                                HttpServletRequest request) throws AppException {

        Map<String, Object> jsonMap = new HashMap<String, Object>();

        if (Utils.notNullAndZero(dto.getTicketDefId())) {
            Ticket ticket = iTicKetDefineService.getTicketById(Long.toString(dto.getTicketDefId()));
            if (MealConstants.VERIFICATION_METHOD_CODE.equals(ticket.getVerificationMethod())) {
                dto.setHasVerificationCode("Y");
            } else if (MealConstants.VERIFICATION_METHOD_N.equals(ticket.getVerificationMethod())) {
                dto.setHasVerificationCode("N");
            }
            MeallineModel meallineModel = iMealManageService.insertMealLineInfo(dto);
            if (meallineModel != null) {
                jsonMap.put("code", true);
                jsonMap.put("msg", "新增成功");
                return jsonMap;
            }
        }
        jsonMap.put("code", false);
        jsonMap.put("msg", "新增失败");
        return jsonMap;
    }

    /**
     * 删除套餐的详细信息
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "removeMealLineInfo")
    @ResponseBody
    public Map<String, Object> removeMealLineInfo(MealDefineDto dto, Model model,
                                                  HttpServletRequest request) throws AppException {

        Map<String, Object> jsonMap = new HashMap<String, Object>();

        List<MeallineModel> meallineList = iMealManageService.getMealLIneInfoByPackageId(dto
            .getPackageDefId());
        if (!meallineList.isEmpty() && meallineList.size() == 1) {
            jsonMap.put("code", false);
            jsonMap.put("msg", "无法删除,必须要保留一行数据");
            return jsonMap;
        }

        iMealManageService.removeMealLineById(dto.getId());
        jsonMap.put("code", true);
        jsonMap.put("msg", "删除成功");
        return jsonMap;
    }

    public void setTicketTypeCode(Ticket ticket) {
        if (CouponConstants.TICKET_TYPE_COUPON.equals(ticket.getTicketType())) {
            ticket.setTicketType("优惠券");
        } else if (CouponConstants.TICKET_TYPE_REDEMPTION.equals(ticket.getTicketType())) {
            ticket.setTicketType("提货券");
        }
    }

    /**
     * 获得入会礼的项目列表
     * @param dto
     * @param ticketList
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    public List<ResultDto> getResultDtoList(MealDefineDto dto, List<Ticket> ticketList)
                                                                                       throws AppException {

        MealDefineDto mealDefineDto = new MealDefineDto();
        mealDefineDto.setIsPhysicalCard(MealConstants.IS_PHYSICAL_CARD_DUMMY);
        List<MealModel> mealModelList = iMealManageService.getMealModelListByParams(mealDefineDto);

        List<ResultDto> resultList = new ArrayList<ResultDto>();
        ResultDto resultDto = null;
        int num = 0;
        for (Iterator iterator = mealModelList.iterator(); iterator.hasNext();) {
            MealModel mealModel = (MealModel) iterator.next();
            resultDto = new ResultDto();
            resultDto.setId(MealConstants.CRAD_TYPE_PACKAGE + "_" + mealModel.getId());
            resultDto.setName(mealModel.getName());
            resultDto.setType(MealConstants.CRAD_TYPE_PACKAGE);
            resultDto.setTypeText(MealConstants.CRAD_TYPE_PACKAGE_TEXT);

            resultList.add(num, resultDto);
            num++;
        }

        for (Iterator iterator = ticketList.iterator(); iterator.hasNext();) {
            Ticket ticket = (Ticket) iterator.next();
            resultDto = new ResultDto();
            resultDto.setId("TICKET_" + ticket.getId());
            String ticketname1 = ticket.getTicketName().replaceAll("\n","");
            String ticketname = ticketname1.replaceAll("\r","");
            resultDto.setName(ticketname);
            resultDto.setType(ticket.getTicketType());
            if (ticket.getTicketType().equals(CouponConstants.TICKET_TYPE_COUPON)) {
                resultDto.setTypeText(CouponConstants.TICKET_TYPE_COUPON_TEXT);
            } else if (ticket.getTicketType().equals(CouponConstants.TICKET_TYPE_REDEMPTION)) {
                resultDto.setTypeText(CouponConstants.TICKET_TYPE_REDEMPTION_TEXT);
            }
            resultList.add(num, resultDto);
            num++;
        }

        return resultList;
    }

    /**
     * 入会礼管理初始化页面
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "toMemberGiftPage")
    public String toMemberGiftPage(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                              throws AppException {

        List<PackageGiftDto> pGiftDtoList = new ArrayList<PackageGiftDto>();
        PackageGiftDto packageGiftDto = null;

        //根据套餐ID查询套餐礼物信息
        List<MemberGiftInfo> meInfoList = iMemberGiftService.getGiftByPackageDefId(dto.getId());
        for (Iterator iterator = meInfoList.iterator(); iterator.hasNext();) {
            MemberGiftInfo memberGiftInfo = (MemberGiftInfo) iterator.next();
            packageGiftDto = new PackageGiftDto();

            packageGiftDto.setId(memberGiftInfo.getId());
            packageGiftDto.setPackageId(memberGiftInfo.getPackageId());
            packageGiftDto.setGiftType(memberGiftInfo.getGiftType());
            packageGiftDto.setGiftId(memberGiftInfo.getGiftId());

            if (MealConstants.CRAD_TYPE_PACKAGE.equals(memberGiftInfo.getGiftType())) {
                //根据套餐ID查询套餐信息
                MealDefineDto mealDefineDto = new MealDefineDto();
                mealDefineDto.setId(memberGiftInfo.getGiftId());
                MealModel mealModel = iMealManageService.getMealInfoById(mealDefineDto);
                packageGiftDto.setGiftName(mealModel.getName());
            } else if (CouponConstants.TICKET_TYPE_COUPON.equals(memberGiftInfo.getGiftType())
                       || CouponConstants.TICKET_TYPE_REDEMPTION.equals(memberGiftInfo
                           .getGiftType())) {
                Ticket ticket = iTicKetDefineService.getTicketById(memberGiftInfo.getGiftId()
                    .toString());
                packageGiftDto.setGiftName(ticket.getTicketName());
            }
            pGiftDtoList.add(packageGiftDto);
        }

        List<ResultDto> resultList = getResultDtoList(dto, iTicKetDefineService.getAllTicketList());
        model.addAttribute("resultList", resultList);
        model.addAttribute("pGiftDtoList", pGiftDtoList);
        model.addAttribute("id", dto.getId());
        model.addAttribute("temp", request.getParameter("temp"));
        model.addAttribute(QNAME, dto.getqName());
        model.addAttribute(QCODE, dto.getqCode());
        model.addAttribute(QSTATUS, dto.getqStatus());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        return "/meal/memberGift";
    }

    /**
     * 入会礼新增
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "saveMermberGiftInfo")
    @ResponseBody
    public Map<String, Object> saveMermberGiftInfo(MermberGiftDto dto, Model model,
                                                   HttpServletRequest request) throws AppException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        if (!"".equals(dto.getGiftStr()) && dto.getGiftStr() != null) {
            String[] gift = dto.getGiftStr().split("###");
            for (int i = 0; i < gift.length; i++) {
                String[] str = gift[i].split("@#");
                String giftName = str[0];
                String giftType = str[1];
                if (giftName.indexOf("_") > 0) {
                    giftName = giftName.substring(giftName.indexOf("_") + 1);
                }
                String giftNameText = str[2];
                MermberGiftDto mermberGiftDto = new MermberGiftDto();
                mermberGiftDto.setPackageId(dto.getPackageId());
                mermberGiftDto.setGiftType(giftType);
                mermberGiftDto.setGiftId(Long.parseLong(giftName));
                MemberGiftInfo memberGiftInfo = iMemberGiftService
                    .getMermberGiftInfo(mermberGiftDto);
                if (memberGiftInfo != null) {
                    jsonMap.put("code", false);
                    jsonMap.put("msg", giftNameText + "入会礼已存在，无法新增");
                    return jsonMap;
                }
            }

            if (iMealManageService.saveMermberGiftInfo(dto)) {
                jsonMap.put("code", true);
                jsonMap.put("msg", "入会礼新增成功");
                return jsonMap;
            }
        } else {
            jsonMap.put("code", false);
            jsonMap.put("msg", "没有新增的数据");
            return jsonMap;
        }
        jsonMap.put("code", false);
        jsonMap.put("msg", "入会礼新增失败");
        return jsonMap;
    }

    /**
     * 入会礼删除
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "removeMermberGift")
    @ResponseBody
    public Map<String, Object> removeMermberGift(MermberGiftDto dto, Model model,
                                                 HttpServletRequest request) throws AppException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        if (iMealManageService.removeMermberGift(dto)) {
            jsonMap.put("code", true);
            jsonMap.put("msg", "删除成功");
            return jsonMap;
        }
        jsonMap.put("code", false);
        jsonMap.put("msg", "删除失败");
        return jsonMap;
    }

    /**
     * 套餐复制初始化页面
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toCopyMealPage")
    public String toCopyMealPage(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                            throws AppException {
        model.addAttribute("dto", dto);
        model.addAttribute(QNAME, dto.getqName());
        model.addAttribute(QCODE, dto.getqCode());
        model.addAttribute(QSTATUS, dto.getqStatus());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        return "/meal/copyMeal";
    }

    /**
     * 套餐复制
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "copyMealInfo")
    @ResponseBody
    public Map<String, Object> copyMealInfo(MealDefineDto dto, Model model,
                                            HttpServletRequest request) throws AppException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        Map<String, Object> map = iMealManageService.saveCopyMealInfo(dto);

        if (map.get("code").equals(true)) {
            jsonMap.put("code", true);
            jsonMap.put("msg", "复制成功");
            jsonMap.put("id", map.get("id"));
            return jsonMap;
        }

        jsonMap.put("code", false);
        jsonMap.put("msg", "复制失败");
        return jsonMap;
    }

    /**
     * 校验套餐编号是否存在
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "checkCode")
    @ResponseBody
    public Map<String, Object> checkCode(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                                    throws AppException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        // 判断套餐是否重复
        MealModel mealModel = iMealManageService.getMealInfoByCode(dto);
        if (mealModel != null) {
            jsonMap.put("msg", "套餐已存在");
            jsonMap.put("code", false);
            return jsonMap;
        }
        return jsonMap;
    }

    /**
     * 套餐启用页面初始化
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toPackageEnabledPage")
    public String toPackageEnabledPage(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                                  throws AppException {
        Pager pager = new Pager();
        pager.setCurrentPage(1);
        MealDefineDto mealDefineDto = new MealDefineDto();
        mealDefineDto.setPager(pager);
        mealDefineDto.setTemp("enabled");
        getMealList(mealDefineDto, model, request);
        return "/meal/packageEnabled";
    }

    /**
     * 套餐启用或停用操作
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "packageEnabled")
    @ResponseBody
    public Map<String, Object> packageEnabled(MealDefineDto dto, Model model,
                                              HttpServletRequest request) throws AppException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();

        MealModel mealModel = iMealManageService.getMealInfoById(dto);

        String msgString = null;
        if (mealModel.getStatus().equals(MealConstants.MEAL_STATUS_DRAFT)) {
            msgString = "启用";
            dto.setStatus(MealConstants.MEAL_STATUS_DRAFT);
        } else if (mealModel.getStatus().equals(MealConstants.MEAL_STATUS_ACTIVE)) {
            msgString = "停用";
            dto.setStatus(MealConstants.MEAL_STATUS_ACTIVE);
        } else if (mealModel.getStatus().equals(MealConstants.MEAL_STATUS_DISCONTINUED)) {
            msgString = "启用";
            dto.setStatus(MealConstants.MEAL_STATUS_DISCONTINUED);
        }

        if (iMealManageService.packageEnabled(dto)) {
            jsonMap.put("code", true);
            jsonMap.put("msg", msgString + "成功");
            return jsonMap;
        }

        jsonMap.put("code", true);
        jsonMap.put("msg", msgString + "失败");
        return jsonMap;
    }

    /**
     * 套餐的适用范围初始化页面
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "toPackageEligibility")
    public String toPackageEligibility(MealDefineDto dto, Model model, HttpServletRequest request)
                                                                                                  throws AppException {
        CodeInfoDto codeInfoDto = new CodeInfoDto();
        codeInfoDto.setType(MealConstants.CODE_TYPE_DEALERPROPERTY);

        List<CodeInfo> codeInfoList = iCodeMapping.getCodeInfoListByParams(codeInfoDto);

        model.addAttribute("codeInfoList", codeInfoList);
        PackageEligibilityDto packageEligibilityDto = new PackageEligibilityDto();
        packageEligibilityDto.setPackageDefId(dto.getPackageDefId());

        List<PackageEligibilityModel> packageEligibilityList = iMealManageService
            .getPackageEligibilityList(packageEligibilityDto);
        
        for (Iterator iterator = packageEligibilityList.iterator(); iterator.hasNext();) {
            PackageEligibilityModel packageEligibilityModel = (PackageEligibilityModel) iterator
                .next();
            String value = iCodeMapping.getCodeValueByCode(MealConstants.CODE_TYPE_DEALERPROPERTY, packageEligibilityModel.getDealerProperty());
            packageEligibilityModel.setDealerProperty(value);
        }

        model.addAttribute("dto", dto);
        model.addAttribute(QNAME, dto.getqName());
        model.addAttribute(QCODE, dto.getqCode());
        model.addAttribute(QSTATUS, dto.getqStatus());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        model.addAttribute("packageEligibilityList", packageEligibilityList);
        model.addAttribute("packageDefId", dto.getPackageDefId());
        model.addAttribute("codeType", MealConstants.CODE_TYPE_DEALERPROPERTY);
        model.addAttribute("temp", request.getParameter("temp"));
        return "/meal/packageEligibility";
    }

    /**
     * 套餐的适用范围新增
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "savePackageEligibilityInfo")
    @ResponseBody
    public Map<String, Object> savePackageEligibilityInfo(PackageEligibilityDto dto, Model model,
                                                          HttpServletRequest request)
                                                                                     throws AppException {
        Map<String, Object> map = new HashMap<String, Object>();

        String priceStr = request.getParameter("priceStr");

        StringBuilder dataString = new StringBuilder();
        if (priceStr != null && !"".equals(priceStr)) {
            String[] data = priceStr.split("###");
            for (int i = 0; i < data.length; i++) {
                String[] pStrings = data[i].split("@#");
                String dealerProperty = pStrings[0];
                String propertyValue = pStrings[1];
                PackageEligibilityDto packageEligibilityDto = new PackageEligibilityDto();
                packageEligibilityDto.setDealerProperty(dealerProperty);
                packageEligibilityDto.setPropertyValue(propertyValue);
                packageEligibilityDto.setPackageDefId(dto.getPackageDefId());
                //检查该适用范围是否已经新增
                PackageEligibilityModel packageEligibilityModel = iMealManageService
                    .getPackageEligibilityInfoByPackageDefId(packageEligibilityDto);
                if (packageEligibilityModel != null) {
                    map.put("code", false);
                    map.put("msg", packageEligibilityModel.getPropertyValue() + "的适用范围已存在");
                    return map;
                }
                dataString.append( dealerProperty + "@#" + propertyValue + "@#" + dto.getPackageDefId()
                              + "@#" + dto.getCodeType() + "###");
            }
        }
        try {
            PackageEligibilityDto packageEligibilityDto = new PackageEligibilityDto();
            packageEligibilityDto.setDataString(dataString.toString());
            iMealManageService.insertPackageEligibilityInfo(packageEligibilityDto);
        } catch (AppException e) {
            LOGGER.error("适用范围新增失败",e);
            map.put("code", false);
            map.put("msg", "适用范围新增失败");
            return map;
        }
        map.put("code", true);
        map.put("msg", "适用范围新增成功");
        return map;
    }

    /**
     * 删除套餐的适用范围信息
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "removePackageEligibility")
    @ResponseBody
    public Map<String, Object> removePackageEligibility(PackageEligibilityDto packageEligibilityDto,
                                                        Model model, HttpServletRequest request)
                                                                                                throws AppException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (iMealManageService.removePackageEligibilityInfo(packageEligibilityDto)) {
            map.put("code", true);
            map.put("msg", "适用范围删除成功");
            return map;
        }
        map.put("code", false);
        map.put("msg", "适用范围删除失败");
        return map;
    }
    
    @RequestMapping(value = "toSelectPackagePage")
    public String toSelectPackagePage(Model model) throws AppException{
    	model.addAttribute("packageDefinitionListDto",
                packageDefinitionService.getAllPackageDefinitionListForSelected());
    	model.addAttribute("dealerId",UserUtil.getCurrentUser().getDealerId());
    	return "/meal/selectPackage";
    }
    
    @RequestMapping(value = "toSelectPackagePageForMars")
    public String toSelectPackagePageForMars(Model model, HttpServletRequest request) throws AppException{
    	model.addAttribute("packageDefinitionListDto",
    			packageDefinitionService.getAllPackageDefinitionListForMars(request.getParameter("dealerId")));
    	model.addAttribute("dealerId",request.getParameter("dealerId"));
    	return "/meal/selectPackage";
    }
    
    @RequestMapping(value = "savePackageSelect")
    @ResponseBody
    public boolean savePackageSelect(Model model, HttpServletRequest request,String parm,String dealerId)throws AppException {
    	try {
			if(StringUtils.isNotBlank(parm) && StringUtils.isNotBlank(dealerId)){
				String parmStr = parm.substring(0, parm.length()-1);
				String[] parms = parmStr.split(",");
				if(parms != null && parms.length>0){
					//删除本店记录
					iMealManageService.removePackageSelected(dealerId);
					for(int i=0; i<parms.length; i++){
						PackageDealerSelected obj = new PackageDealerSelected();
						obj.setDealerId(Integer.parseInt(dealerId));
						obj.setPackageDefId(Long.parseLong(parms[i]));
						//重新存储本店记录
						iMealManageService.savePackageSelected(obj);
					}
				}
				return true;
			}
			if("".equals(parm)){
				iMealManageService.removePackageSelected(dealerId);
				return true;
			}
		} catch (Exception e) {
			LOGGER.error("savePackageSelect ERROR" + e);
		}
    	return false;
    }
}
